package com.etymgiko.lyricshere.web.admin.artist;

import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import com.etymgiko.lyricshere.manager.ArtistManager;
import com.etymgiko.lyricshere.model.Artist;

/**
 *
 * @author Ivan Holub
 */
public class ArtistValidator implements Validator {

    private ArtistManager artistManager;

    public void setArtistManager(ArtistManager artistManager) {
        this.artistManager = artistManager;
    }

    public boolean supports(Class clazz) {
        return true;
    }

    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.arist.name.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "code", "error.arist.code.required");

        ArtistCommand command = (ArtistCommand) target;

        Artist artist = artistManager.findArtistByName(command.getName());
        if (artist != null) {
            Long id = command.getId() == null ? null : Long.valueOf(command.getId());
            if (artist.getName().equals(command.getName()) && !artist.getId().equals(id)) {
                errors.rejectValue("name", "error.arist.name.duplicate");
            }
        }

        artist = artistManager.findArtistByCode(command.getCode());
        if (artist != null) {
            Long id = command.getId() == null ? null : Long.valueOf(command.getId());
            if (artist.getCode().equals(command.getCode()) && !artist.getId().equals(id)) {
                errors.rejectValue("code", "error.arist.code.duplicate");
            }
        }
    }
}
